//
//  BPSearchMapViewController.m
//  BP_NewClient
//
//  Created by letv on 15/7/19.
//  Copyright (c) 2015年 normal. All rights reserved.
//  查找路线-高德地图

#import "BPSearchMapViewController.h"
#import "Constants.h"
#import "UIView+Addition.h"
@interface BPSearchMapViewController ()

@end

@implementation BPSearchMapViewController

/* 初始化search. */
- (void)initSearch
{
    self.search = [[AMapSearchAPI alloc] initWithSearchKey:[MAMapServices sharedServices].apiKey Delegate:nil];
}

#pragma mark - Life Cycle

- (id)init
{
    if (self = [super init])
    {
        
    }
    return self;
}

- (void)setStartEndAnnotion{
    _startAnnotation = [[MAPointAnnotation alloc] init];
    _startAnnotation.coordinate = CLLocationCoordinate2DMake(39.924693, 116.389771);
    _startAnnotation.title = @"start";
    [self.mapView addAnnotation:_startAnnotation];
    
    _endAnnotation = [[MAPointAnnotation alloc] init];
    _endAnnotation.coordinate = CLLocationCoordinate2DMake(39.904693, 116.439771);
    _endAnnotation.title = @"end";
    [self.mapView addAnnotation:_endAnnotation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    /* 初始化search. */
    [self initMapView];
    [self initSearch];
    [self setStartEndAnnotion];
    
    UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
    btnBack.frame = CGRectMake(12.5, 33, 60, 35);
    btnBack.backgroundColor = [UIColor clearColor];
    [btnBack setTitle:@"反回" forState:UIControlStateNormal];
    btnBack.titleLabel.font = [UIFont systemFontOfSize:15];
    [btnBack setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [btnBack setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [btnBack addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnBack];
    
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    [self.mapView setZoomLevel:20 animated:YES];
    [self setNavigationToolView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)setNavigationToolView{
    
    UIView *toolView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight - 135, ScreenSize.width, 135)];
    toolView.backgroundColor = [BPCommon colorWithHexValue:0xffffff alpha:1.0f];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(12.5, 15, 200, 20)];
    title.text = @"佳格美发沙龙";
    title.textColor = [BPCommon colorWithHexValue:0x3b3b3b alpha:1.0f];
    title.font = [UIFont systemFontOfSize:15];
    
    UILabel *address = [[UILabel alloc] initWithFrame:CGRectMake(12.5, title.bottom + 10, 200, 20)];
    address.textColor = [BPCommon colorWithHexValue:0xc7c7c7 alpha:1.0f];
    address.text = @"朝阳区光华路朝阳公园桥东500米";
    address.font = [UIFont systemFontOfSize:13];

    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn1.frame = CGRectMake(12.5, address.bottom + 13, 90, 35);
    btn1.backgroundColor = [BPCommon colorWithHexValue:0xf9f9f9 alpha:1.0f];
    [btn1 setTitle:@"查找路线" forState:UIControlStateNormal];
    btn1.titleLabel.font = [UIFont systemFontOfSize:15];
    [btn1 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [btn1 addTarget:self action:@selector(findPath) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn2.frame = CGRectMake(btn1.right + 12 , address.bottom + 13, 90, 35);
    btn2.titleLabel.font = [UIFont systemFontOfSize:15];
    btn2.backgroundColor = [BPCommon colorWithHexValue:0xf9f9f9 alpha:1.0f];
    [btn2 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [btn2 setTitle:@"本机地图" forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(findPathByPhone) forControlEvents:UIControlEventTouchUpInside];

    btn1.layer.cornerRadius = 4;
    btn1.layer.borderColor = [UIColor lightGrayColor].CGColor;
    btn1.layer.borderWidth = 0.5;
    
    btn2.layer.cornerRadius = 4;
    btn2.layer.borderColor = [UIColor lightGrayColor].CGColor;
    btn2.layer.borderWidth = 0.5;

    [toolView addSubview:title];
    [toolView addSubview:address];
    [toolView addSubview:title];

    [toolView addSubview:btn1];
    [toolView addSubview:btn2];

    [self.view addSubview:toolView];
}

// 查找本机地图
- (void)findPathByPhone{

    if ([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:@"baidumap://map/"]]){
        hasBaiduMap = @"使用百度地图导航";
    }
    if ([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:@"iosamap://"]]){
        
        hasGaodeMap = @"使用高德地图导航";
    }
    
    if (hasBaiduMap || hasGaodeMap) {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:hasBaiduMap,hasGaodeMap, nil];
        [sheet showInView:self.view];
    }else {
    
        [self showNoticeMsg:@"请安装百度或者高德地图"];
    }
 
}

#pragma - mark
#pragma - mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (hasBaiduMap && hasGaodeMap) {
        
        if (buttonIndex == 0) {
            [self findPathBaidu];
        }else if (buttonIndex == 1){
            [self findPathGaode];
        }
        
    }else if (hasBaiduMap){
      
        if (buttonIndex == 0) {
            [self findPathBaidu];
        }
    
    }else if (hasGaodeMap){

        if (buttonIndex == 0) {
            [self findPathGaode];
        }
        
    }else{
    
        // TODO : NOTHING
    }
    
    hasBaiduMap = nil;
    hasGaodeMap = nil;
}


// 高德地图
- (void)findPathGaode{
    [self baiduOrGaodeMap:@"使用高德地图导航" StartCoordinate:_startAnnotation.coordinate EndCoordinate:_endAnnotation.coordinate];
}

- (void)findPathBaidu{
    [self baiduOrGaodeMap:@"使用百度地图导航" StartCoordinate:_startAnnotation.coordinate EndCoordinate:_endAnnotation.coordinate];
}

- (void)baiduOrGaodeMap:(NSString *)title StartCoordinate:(CLLocationCoordinate2D)startCordinate EndCoordinate:(CLLocationCoordinate2D)endCoordinate{

    if ([@"使用百度地图导航" isEqualToString:title])
    {
        NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin=latlng:%f,%f|name:我的位置&destination=latlng:%f,%f|name:终点&mode=driving",startCordinate.latitude, startCordinate.longitude, endCoordinate.latitude,endCoordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ;
        
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString]];
    }
    else if ([@"使用高德地图导航" isEqualToString:title])
    {
        MARouteConfig *config = [MARouteConfig new];
        config.appName = [self getApplicationName];
        config.appScheme = [self getApplicationScheme];
        config.startCoordinate = _startAnnotation.coordinate;
        config.destinationCoordinate = _endAnnotation.coordinate;
        config.routeType = MARouteSearchTypeDriving;
        [MAMapURLSearch openAMapRouteSearch:config];
        //        NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&poiname=%@&lat=%f&lon=%f&dev=1&style=2",@"app name", @"众人美发", @"终点",endCoordinate.latitude,endCoordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        //
        //        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString]];
    }
}

#pragma mark - MAMapViewDelegate

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
        }
        annotationView.canShowCallout               = YES;
        annotationView.animatesDrop                 = YES;
        
        if (annotation == _startAnnotation)
        {
            annotationView.pinColor = MAPinAnnotationColorGreen;
        }
        else
        {
            annotationView.pinColor = MAPinAnnotationColorRed;
        }
        return annotationView;
    }
    return nil;
}

#pragma -mark MAMapViewDelegate
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation
{
    //取出当前位置的坐标
//    NSLog(@"latitude : %f,longitude: %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
}

- (void)mapView:(MAMapView *)mapView didFailToLocateUserWithError:(NSError *)error{
    
    NSDictionary *dic = @{@"status":@"0",@"description":error.description};
    NSLog(@"dic is %@",dic);

}

- (void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    MAAnnotationView *view = views[0];
    
    // 放到该方法中用以保证userlocation的annotationView已经添加到地图上了。
    if ([view.annotation isKindOfClass:[MAUserLocation class]])
    {
        MAUserLocationRepresentation *pre = [[MAUserLocationRepresentation alloc] init];
        pre.fillColor = [UIColor colorWithRed:0.9 green:0.1 blue:0.1 alpha:0.3];
        pre.strokeColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.9 alpha:1.0];
        pre.image = [UIImage imageNamed:@"AMap.bundle/redPin.png"];
        pre.lineWidth = 3;
        pre.lineDashPattern = @[@6, @3];
        
        [self.mapView updateUserLocationRepresentation:pre];
        
        view.calloutOffset = CGPointMake(0, 0);
    } 
}



- (void)MASearchPathWithLocation:(CLLocationCoordinate2D)startLocation FinalLocation:(CLLocationCoordinate2D)endLocation{
    
}

- (void)MASearchPathWithAddress:(CLLocationCoordinate2D)startLocation FinalLocation:(NSString *)endAddress{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
